﻿using Hx.ADSyncPlatform.Common.Config;
using Hx.ADSyncPlatform.Db;
using Hx.ADSyncPlatform.Infrastructure;
using Hx.ADSyncPlatform.InfrastructureSecurity;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;

namespace Hx.ADSyncPlatform.SqlSugar
{
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {

            if (services == null) throw new ArgumentNullException(nameof(services));

            // 把多个连接对象注入服务，这里必须采用Scope，因为有事务操作
            string connectionString = Encrypt.AESDecrypt(AppSettings.Configuration["DbConnection:ConnectionString"], EncryptKey.Key);
            var db = new SqlSugarClient(new ConnectionConfig()
            {

                ConnectionString = connectionString,
                DbType = Enum.Parse<DbType>(AppSettings.Configuration["DbConnection:DbType"]),
                IsAutoCloseConnection = true,
                IsShardSameThread = true,
                InitKeyType = InitKeyType.Attribute,
                //ConfigureExternalServices = new ConfigureExternalServices()
                //{
                //    DataInfoCacheService = new RedisCache()
                //},
                MoreSettings = new ConnMoreSettings()
                {
                    IsAutoRemoveDataCache = true
                }
            }); ; ;
            //调式代码 用来打印SQL 
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql);
            };

            //db.DbMaintenance.CreateDatabase();
            //db.CodeFirst.InitTables(typeof(Plat_OperateLog));
            services.AddScoped<DbContext>(o =>
            {

                return new DbContext() { Db = db };
            });


        }
    }
}
